[assembly: WebActivator.PostApplicationStartMethod(typeof(FileDownloadServer.App_Start.SimpleInjectorInitializer), "Initialize")]

namespace FileDownloadServer.App_Start
{
	using System.Reflection;
	using System.Web.Mvc;

	using SimpleInjector;
	using System.Collections.Concurrent;
	using System;
	using System.Web.Http;
	
	public class SimpleInjectorInitializer
	{
		private readonly Container container = new Container();

		/// <summary>Initialize the container and register it as MVC3 Dependency Resolver.</summary>
		public static void Initialize()
		{
			new SimpleInjectorInitializer().Initialise();
		}

		private void Initialise()
		{
			RegisterServices();
			RegisterControllers();
			container.Verify();

			GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
		}

		private void RegisterControllers()
		{
			var services = GlobalConfiguration.Configuration.Services;
			var controllerTypes = services.GetHttpControllerTypeResolver()
				.GetControllerTypes(services.GetAssembliesResolver());

			foreach (var controllerType in controllerTypes)
				container.Register(controllerType);
		}
	 
		private void RegisterServices()
		{
			container.RegisterSingle<ConcurrentDictionary<string, FileDownloadProperties>>(MakeDownloadRepository);
		}
		
		private static ConcurrentDictionary<string, FileDownloadProperties> MakeDownloadRepository()
		{
			return new ConcurrentDictionary<string, FileDownloadProperties>(StringComparer.Ordinal);
		}
	}
}